﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.IO;

namespace Pda_Total_Station
{
    public partial class Mfrm : Form
    {
        #region 全局变量
        DataBase m_db;
        GeoCom geocom;
        svtps mytps;
        #endregion
        string datetime_str(DateTime time)
        {
            string str = time.ToString("M-d-yyyy HH:mm:ss");
            return str;
        }
        public Mfrm()
        {
            InitializeComponent();
            DataBase db = null;
            string str = datetime_str(DateTime.Now);
            if (DataBase.ConnectToDataBase("LevelData.sdf", ref db))
            {
                m_db = db;
            }

            if (!m_db.IsTableInDataBase("projects"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("projects", list);
            }
            //m_db.DeleteTable("datalog");
            if (!m_db.IsTableInDataBase("datalog"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("turn", "integer", "not null");
                list.Add(fild);
                fild = new DataField("angle", "float", "not null");
                list.Add(fild);
                fild = new DataField("slope", "float", "not null");
                list.Add(fild);
                fild = new DataField("height", "float", "not null");
                list.Add(fild);
                fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("datalog", list);
            }
            if (!m_db.IsTableInDataBase("dataconfig"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("id", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("E", "float", "not null");
                list.Add(fild);
                fild = new DataField("N", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("dataconfig", list);
            }

        }
        #region 第一页
        //打开串口
        private void bConnect_Click(object sender, EventArgs e)
        {
            if (Combox.Text.Equals(string.Empty))
            {
                MessageBox.Show("请选择COM口");
                return;
            }
            try
            {
                string com = Combox.Text;
                if (geocom != null && geocom.port.IsOpen)
                {
                    geocom.port.Close();
                }
                geocom = new GeoCom(com);
                bConnect.Enabled = false;
                bDisConnect.Enabled = true;
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }
        //关闭串口
        private void bDisConnect_Click(object sender, EventArgs e)
        {
            try
            {
                geocom.port.Close();
                bConnect.Enabled = true;
                bDisConnect.Enabled = false;
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }

        }

        //获取测站坐标
        private void btn_getstn_Click(object sender, EventArgs e)
        {
            string str = geocom.Get_Station();
            if (str != "0")
            {
                string[] v = str.Split(',');
                textBox1.Text = v[0];
                textBox2.Text = v[1];
                textBox3.Text = v[2];
                textBox4.Text = v[3];
            }
            else
            {
                MessageBox.Show("获取测站失败");
            }
        }

        private void btnok1_Click(object sender, EventArgs e)
        {
            svpoint pt = new svpoint("center", Convert.ToDouble(textBox1.Text),
                Convert.ToDouble(textBox2.Text), Convert.ToDouble(textBox2.Text));
            mytps = new svtps(pt, Convert.ToDouble(textBox4.Text));
            tabControl1.SelectedIndex = 1;
        }
        #endregion
        #region 第二页
     
        //新建工程
        private void btnaddprj_Click(object sender, EventArgs e)
        {
            string name = textBox5.Text;
            if (name == string.Empty)
            {
                MessageBox.Show("工程名称不能为空!");
                return;
            }
           
            int i = comprj.Items.IndexOf(name);
            if (i >= 0)
            {
                MessageBox.Show("工程名称已存在!");
                return;
            }
            string sql = "select * from [projects]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            int ii = dt.Rows.Count + 1;
            cur_id = ii;
            sql = "Insert into [projects] values('" + datetime_str(DateTime.Now) + "','" + name + "'," + cur_id + ")";
            m_db.ExecuteSQL(sql);
            grid_config.DataSource = null;
            textBox5.Text = string.Empty;
            comprj.Items.Add(name);
            comprj.Text = name;
            MessageBox.Show("新建成功");
        }
        int cur_id = -1;
        //选择了工程
        private void comprj_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comprj.SelectedIndex < 0)
            {
                return;
            }
            string name = comprj.Items[comprj.SelectedIndex].ToString();
            string sql = "select [id] from [projects] where [name]='" + name + "'";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            int id = Convert.ToInt32(dt.Rows[0][0]);
            cur_id = id;
            sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + id;
            dt = m_db.GetDataSet(sql).Tables[0];
            grid_config.DataSource = dt;
        }
        //点击data_config事件
        private void grid_config_Click(object sender, EventArgs e)
        {
            int index = grid_config.CurrentRowIndex;
            if (index < 0)
            {
                return;
            }
            DataTable dt = grid_config.DataSource as DataTable;
            string name = dt.Rows[index][0].ToString();
            txt_new_pt.Text = name;

        }
        //双击data_config事件
        private void grid_config_DoubleClick(object sender, EventArgs e)
        {
            int index = grid_config.CurrentRowIndex;
            if (index < 0)
            {
                return;
            }
            DataTable dt = grid_config.DataSource as DataTable;
            dt.Rows.RemoveAt(index);
            grid_config.DataSource = dt;
        }

        //添加新的学习点
        private void btn_add_pt_Click(object sender, EventArgs e)
        {
            try
            {
                string str = geocom.Measure_Distance_Angle();
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    svpoint pt = mytps.PolarToXYZ(Convert.ToDouble(v[0]), Convert.ToDouble(v[1]), Convert.ToDouble(v[2]));
                    pt.name = txt_new_pt.Text;
                    string sql = "insert into [dataconfig] values(" + cur_id + ",'" + pt.name + "'," + pt.E + "," + pt.N + "," + pt.H + ")";
                    m_db.ExecuteSQL(sql);
                    sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + cur_id;
                    DataTable dt = m_db.GetDataSet(sql).Tables[0];
                    grid_config.DataSource = dt;
                }
                else
                {
                    MessageBox.Show("添加失败");
                }

            }
            catch
            {
                MessageBox.Show("添加失败");
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                string name = txt_new_pt.Text;
                string sql = "delete from [dataconfig] where [id]=" + cur_id + " and [name]='" + name + "'";
                m_db.ExecuteSQL(sql);
                sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + cur_id;
                DataTable dt = m_db.GetDataSet(sql).Tables[0];
                grid_config.DataSource = dt;

            }
            catch
            {
                MessageBox.Show("删除失败");
            }

        }
        #endregion
        #region index变化
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                comprj.Items.Clear();
                string sql = "select [name] from [projects]";
                DataTable dt = m_db.GetDataSet(sql).Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string name = dt.Rows[i][0].ToString();
                    comprj.Items.Add(name);
                }
            }
            else if (tabControl1.SelectedIndex == 2)
            {
                DataTable dt = grid_config.DataSource as DataTable;
                if (dt.Rows.Count == 0 || comprj.Text == string.Empty)
                {
                    MessageBox.Show("工程和学习点不能为空");
                }
                else
                {
                    mytps.points  = new List<svpoint>(dt.Rows.Count);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        svpoint pt = new svpoint(dt.Rows[i][0].ToString(), Convert.ToDouble(dt.Rows[i][1]), Convert.ToDouble(dt.Rows[i][2]),
                            Convert.ToDouble(dt.Rows[i][3]));
                        mytps.points.Add(pt);
                    }
                }
            }
            else if (tabControl1.SelectedIndex == 3)
            {
                show_data();
            }
            else if (tabControl1.SelectedIndex == 4)
            {
                load_pt_names();
            }
        }
        #endregion

        #region 第三页
        //开始测量
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (comboturn.SelectedIndex < 0)
            {
                MessageBox.Show("测回数不能为空!");
                return;
            }
            //Thread thr = new Thread(new ThreadStart(take_turns));
            //thr.Start();
            take_turns();

        }
        void parse(string txt)
        {
            txtdata.Text += txt;
            txtdata.SelectionStart = txtdata.Text.Length;
            txtdata.ScrollToCaret();
        }
        void take_turns()
        {
            int count = Convert.ToInt32(comboturn.Text);
            mytps.myturn = new turns();
            mytps.myturn.Count = count;
            mytps.myturn.turn_list = new List<turn>(count);
            mytps.curface = Face.face1;
           
            //开始测回观测
            for (int i = 0; i < count; i++)
            {
            again:
                string msg = string.Empty;
                mytps.curface = Face.face1;
                one_turn_survey(i);
                mytps.curface = Face.face2;
                one_turn_survey(i);
                bool ok = mytps.myturn.turn_list[i].check(ref msg);
                if (ok == false)
                {
                    if (MessageBox.Show(msg, "超限", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        goto again;
                    }
                }

            }
            //bool success = mytps.myturn.check(ref msg);
            //if (success == false)
            //{
            //    MessageBox.Show(msg);
            //    take_turns();
            //}
            mytps.get_value();
        }

        void one_turn_survey(int i)
        {
            string msg = string.Empty;
            string cmd = string.Empty;
            string str = string.Empty;
            string face = string.Empty;
            if (mytps.curface == Face.face1)
            {
                face = "正镜";
                turn this_turn = new turn(mytps.points.Count);
                try
                {
                    mytps.myturn.turn_list.Insert(i, this_turn);
                }
                catch
                {

                }
            }
            else
            {
                face = "倒镜";
            }

            List<int> unsurvey = new List<int>();
            for (int j = 0; j < mytps.points.Count; j++)
            {
                try
                {
                    if (mytps.myturn.turn_list[i].pts[j] != null && mytps.myturn.turn_list[i].pts[j].check == true)
                    {
                        continue;
                    }
                }
                catch
                { }
                msg = "第" + (i + 1).ToString() + "测回," + face + ",点名:" + mytps.points[j].name + ":\r\n";
                parse(msg);
                double hz = mytps.getAzim(j);
                double hv = mytps.getVertA(j);
                cmd = hz.ToString() + "," + hv.ToString();
                geocom.Make_Postion1(cmd);
                Thread.Sleep(1000);
                Thread.Sleep(600);
                str = geocom.Measure_Distance_Angle();
                Thread.Sleep(1000);
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    svpoint p = new svpoint();
                    if (mytps.curface == Face.face1)//如果是正镜
                    {
                       
                        p.name = mytps.points[j].name;
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        p.time = DateTime.Now;
                        mytps.myturn.turn_list[i].pts.Add(p);
                    }
                    else//如果是倒镜
                    {
                        try
                        {
                            p.Hz1 = Convert.ToDouble(v[0]);
                            p.Hv1 = Convert.ToDouble(v[1]);
                            p.slope1 = Convert.ToDouble(v[2]);
                            mytps.myturn.turn_list[i].pts[j].Hz2 = Convert.ToDouble(v[0]);
                            mytps.myturn.turn_list[i].pts[j].Hv2 = Convert.ToDouble(v[1]);
                            mytps.myturn.turn_list[i].pts[j].slope2 = Convert.ToDouble(v[2]);
                            mytps.myturn.turn_list[i].pts[j].check = true;
                        }
                        catch
                        { }
                    }
                    svpoint pp = mytps.PolarToXYZ(p.Hz1, p.Hv1, p.slope1);
                    //msg = "E:" + Math.Round(pp.E, 4) + ",N:" + Math.Round(pp.N, 4) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    msg = "Hv:" + Math.Round(p.Hv1, 7) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    parse(msg);
                }
                else
                {
                    unsurvey.Add(j);
                }
            }
            //开始重测
            for (int j = 0; j < unsurvey.Count; j++)
            {
                msg = "重测第" + (i + 1).ToString() + "测回," + face + ",点名:" + mytps.points[unsurvey[j]].name + ":\r\n";
                parse(msg);
                double hz = mytps.getAzim(unsurvey[j]);
                double hv = mytps.getVertA(unsurvey[j]);
                cmd = hz.ToString() + "," + hv.ToString();
                geocom.Make_Postion1(cmd);
                Thread.Sleep(600);
                str = geocom.Measure_Distance_Angle();
                Thread.Sleep(1000);
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    svpoint p = new svpoint();
                    if (mytps.curface == Face.face1)
                    {

                        p.name = mytps.points[unsurvey[j]].name;
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        p.time = DateTime.Now;
                        mytps.myturn.turn_list[i].pts.Insert(unsurvey[j], p);
                    }
                    else
                    {
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].Hz2 = Convert.ToDouble(v[0]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].Hv2 = Convert.ToDouble(v[1]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].slope2 = Convert.ToDouble(v[2]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].check = true;
                    }
                    svpoint pp = mytps.PolarToXYZ(p.Hz1, p.Hv1, p.slope1);
                    //msg = "E:" + Math.Round(pp.E, 4) + ",N:" + Math.Round(pp.N, 4) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    msg = "Hv:" + Math.Round(p.Hv1, 7) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    parse(msg);
                }
                else
                {
                    if (mytps.curface == Face.face1)
                    {
                        svpoint p = new svpoint();
                        p.name = mytps.points[unsurvey[j]].name;
                        mytps.myturn.turn_list[i].pts.Insert(unsurvey[j], p);
                    }
                    msg = "无法观测,放弃...";
                    parse(msg);
                }
            }

        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString())
                + "\\" + DateTime.Now.ToShortDateString()  + ".txt";
            using (StreamWriter sw = new StreamWriter(path,true))
            {
             
                sw.WriteLine(txtdata.Text);
                sw.Close();
                txtdata.Text = "";
                MessageBox.Show("保存文本文件成功");
            }

        }
        private void btn_clear_Click(object sender, EventArgs e)
        {
            txtdata.Text = string.Empty;
        }
        #endregion

        private void Mfrm_Closed(object sender, EventArgs e)
        {
            try
            {
                if (geocom != null && geocom.port.IsOpen == true)
                {
                    geocom.port.Close();
                }
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }

        #region 第四页
        void show_data()
        {
            if (geocom == null || mytps == null || mytps.myturn.turn_list == null || mytps.myturn.turn_list.Count == 0 || mytps.myturn.turn_list[0].pts == null)
            {
                return;
            }
            int cc = mytps.myturn.turn_list[0].pts.Count;
            if (cc == 0)
            {
                return;
            }

            DataTable tt = new DataTable();
            tt.Columns.Add("点名"); tt.Columns.Add("H"); 
            for (int i = 0; i < cc; i++)
            {
                object[] para = new object[2];
                para[0]=mytps.myturn.turn_list[0].pts[i].name;
                para[1] = mytps.myturn.turn_list[0].pts[i].H;
                string sql = "insert into [datalog] values(" + cur_id + ",'" + mytps.myturn.turn_list[0].pts[i].name + "',0," + mytps.myturn.turn_list[0].pts[i].Hv +
                    "," + mytps.myturn.turn_list[0].pts[i].slope + "," + mytps.myturn.turn_list[0].pts[i].H + ",'" + datetime_str(mytps.myturn.turn_list[0].pts[i].time) + "')";
                tt.Rows.Add(para);
                m_db.ExecuteSQL(sql);
            }
            gird_result.DataSource = tt;
            mytps.myturn = new turns();
            picker2.Value = DateTime.Now;
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            DateTime t1 = picker1.Value;
            DateTime t2 = picker2.Value;
            string sql = "Select [name] as [点名],[height] as [H],[time] as [时间] from [datalog] where time between '" + datetime_str(t1) + "' and '" +
                datetime_str(t2) + "'";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            gird_result.DataSource = dt;
           

        }
        #endregion


        #region 第五页
        void load_pt_names()
        {
            //if (cur_id == -1)
            //{
            //    return;
            //}
            combo_names.Items.Clear();
            string sql = "select [name] from [datalog] where [prjid]=" + cur_id + " group by [name]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                combo_names.Items.Add(dt.Rows[i][0]);
            }

        }
        #endregion

        private void combo_names_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = combo_names.SelectedIndex;
            if (i < 0)
            {
                return;
            }
            string name = combo_names.Items[i].ToString();
            string sql = "select [height],[time] from [datalog] where [name]='" + name + "'order by [time]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            mygraph graph = new mygraph();
            Image image = graph.Render(name + "历史曲线", pictureBox1.Width, pictureBox1.Height, dt, name);
            pictureBox1.Image = image;

        }

        private void Mfrm_Deactivate(object sender, EventArgs e)
        {
            this.Close(); 
        }












    }
}